package com.region.b.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.region.b.service.itf.B1001_ITF;
import com.syf.core.service.SyService;
import com.syf.core.service.SyServiceSetting;
import com.syf.core.service.context.ServiceContext;
import com.syf.core.service.context.ServiceResponse;
import com.syf.kit.SyfJsonMapper;
import com.syf.kit.SyfJsonMapperFactory;
import com.syf.kit.soa.core.SyfRemoteServiceInvoker;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@SyServiceSetting(code = "B1001", desc = "test-region-调用，正常返回")
public class B1001 implements SyService<B1001_ITF.ReqData, B1001_ITF.RespData> {

    @Override
    public void execute(ServiceContext<B1001_ITF.ReqData, B1001_ITF.RespData> ctx) {
        log.info("交易码为{}", ctx.getRequest().getHead().getServiceDefinition().getServiceCode());
        B1001_ITF.ReqData reqDataObj = ctx.getRequest().getDataObj();

        SyfJsonMapperFactory jsonMapperFactory = ctx.getToolKit(SyfJsonMapperFactory.class);

        /**
         * 可以新建一个objectMapper
         * */
        ObjectMapper objectMapper = jsonMapperFactory.getUnifiedJsonMapper().getObjectMapper().copy();
        SyfJsonMapper jsonMapper = jsonMapperFactory.getCustomizedJsonMapper(objectMapper);

        log.info("请求报文的json字符串为{}", jsonMapper.toJsonString(reqDataObj));

        // 远程调用
        SyfRemoteServiceInvoker remoteInvoker = ctx.getToolKit(SyfRemoteServiceInvoker.class);
        Map<String, Object> callReqMap = new HashMap<>();
        callReqMap.put("orderName", "测试订单");
        callReqMap.put("orderAmt", 250);
        callReqMap.put("orderDesc", "测试订单xxx-desc");

        ServiceResponse<Map<String, Object>> rpcResp = remoteInvoker.callRemoteService("regionA", "A1002", callReqMap, ctx);
        if (!rpcResp.isSuccess()) {
            log.error("调用远程交易:[regionA][A1002]失败，失败错误码：{}，错误描述：{}", rpcResp.getRespCode(), rpcResp.getRespMsg());
            ctx.getResponse().setError("BIZ1002", "调用交易失败：" + rpcResp.getRespMsg());
            return;
        }

        ctx.getResponse().setSuccess();
        B1001_ITF.RespData respDataObj = new B1001_ITF.RespData();
        respDataObj.setRespParam1("测试返回!");
        ctx.getResponse().setDataObj(respDataObj);
    }
}
